package com.yb0os1.minispring.design;

import com.yb0os1.minispring.anno.AutoWired;
import com.yb0os1.minispring.anno.Component;
import com.yb0os1.minispring.anno.PostConstruct;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

//设计图 bean有名字 构造函数 依赖关系
public class BeanDefinition {

    private final Class<?> beanType;
    private final String name;

    private final Constructor<?> constructor;
    private final Method postConstructMethod;
    private final List<Field> autowiredFiles;

    public BeanDefinition(Class<?> type) {//bean的类型
        Component component = type.getAnnotation(Component.class);
        try {
            this.beanType = type;
            this.name = component.name().isEmpty() ? type.getSimpleName() : component.name();
            this.constructor = type.getDeclaredConstructor();
            this.postConstructMethod = Arrays.stream(type.getDeclaredMethods()).filter(t -> t.isAnnotationPresent(PostConstruct.class)).findFirst().orElse(null);
            this.autowiredFiles = Arrays.stream(type.getDeclaredFields()).filter(t -> t.isAnnotationPresent(AutoWired.class)).toList();
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }

    public String getName() {
        return this.name;
    }
    public Class<?> getBeanType() {
        return beanType;
    }
    public Constructor<?> getConstructor() {
        return this.constructor;
    }


    public Method getPostConstructMethod() {
        return postConstructMethod;
    }

    public List<Field> getAutowiredFields() {
        return autowiredFiles;
    }
}
